<?php

namespace User\Controller;

use Think\Controller;

class CapitalController extends  Controller{

    //入金
    public function Into_Gold(){
        $user = session('user');
        if(empty($user)){redirect('Index/login', 1, '身份信息过期，正在跳转登录页面...');}    //session为空跳转到登陆页
        $userState=M('user')->where(['user_id'=>$user['user_id']])->field('status')->find();
        if($userState['status']!=3){
            die('您的账号还未进行实名认证申请，请实名认证通过后在进行入金');
        }
        $set = M('into_gold_set')->where(['state'=>1])->find();
        $set['remarks']= htmlspecialchars_decode($set['remarks']);//入金说明

        $this->assign('set',$set);
        $this->assign('user',$user);
        $this->display();
    }

    /**
     *  POB支付
     *
     */
    //入金提交
    public function Into_gold_pay(){
        $user = session('user');
        if(empty($user)){redirect('Index/login', 1, '身份信息过期，正在跳转登录页面...');}    //session为空跳转到登陆页
        $set = M('into_gold_set')->where(['belong_pay'=>1])->find();
        $money = I('usd')?I('usd'):die("入金金额不得为空");
        $bank = I('bank')?I('bank'):'baomt';//支付银行码
        if($bank!='02'){die('Channel error, please try again!');}
        $data['appType']=$bank;//支付方式
        $data['cardType']=I('cardType') ? I('cardType') : 'baomt';//支付卡种
        if(!is_numeric($money)){echo "<font color='red'>交易金额必须是数字。</font>";exit;}
        if($money<$set['minimum']){echo "<font color='red'>入金金额不得低于".$set['minimum']."</font>";exit;}

        $add['mt4'] = $user['user_id'];
        $add['money'] = round($money,2);
        $add['rate'] = $set['rate'];
        $add['modu'] = $set['name'];
        $add['into_time'] = time();
		//if($user['user_id']!=250107){die;}
        $into_add = M('into_gold')->add($add);
        if($into_add){
            $merchantID='1005632168';//商户号
            $appsecret ='24AaCdb1eBDc03E';
            $merOrderNum = $into_add.'-'.$user['user_id'];      //订单号**********
            $tranAmt = round($add['money']*$set['rate'],2);                //交易金额*********
            $frontMerUrl =  'http://www.airgio.com/index.php/User/Capital/return_html';//商户前台通知地址**********
            $backgroundMerUrl = 'http://www.airgio.com/index.php/User/Capital/NJ_Pay_return';//商户后台通知地址**********
			
			if($bank=='02'){
				$serverUrl ='http://www.4dvd.cn/App/Test/payView';
				$html = "<form name='toPay' action='" .$serverUrl . "' method='POST'>\r";
				$html .= "<input type='hidden' name='merchant' value='" . $merchantID . "'>\r";
				$html .= "<input type='hidden' name='merOrderNum' value='" . $merOrderNum . "'>\r";
				$html .= "<input type='hidden' name='tranAmt' value='" . $tranAmt . "'>\r";
				$html .= "<input type='hidden' name='mt4' value='" .$user['user_id'] . "'>\r";
				$html .= "</form>";
				$html .= "<script>document.forms['toPay'].submit();</script>";
				echo $html;
			}else{
				$serverUrl ='http://www.4dvd.cn/App/Aggregate/index';
				$html = "<form name='toPay' action='" .$serverUrl . "' method='POST'>\r";
				$html .= "<input type='hidden' name='merchantID' value='" . $merchantID . "'>\r";
				$html .= "<input type='hidden' name='merOrderNum' value='" . $merOrderNum . "'>\r";
				$html .= "<input type='hidden' name='tranAmt' value='" . $tranAmt . "'>\r";
				$html .= "<input type='hidden' name='secret_key' value='" . $appsecret . "'>\r";
				$html .= "<input type='hidden' name='frontMerUrl' value='" . $frontMerUrl . "'>\r";
				$html .= "<input type='hidden' name='backgroundMerUrl' value='" . $backgroundMerUrl . "'>\r";
				$html .= "</form>";
				$html .= "<script>document.forms['toPay'].submit();</script>";
				echo $html;
			}
        }else{
            echo('系统出错,请联系客服');
        }

    }
    //页面返回
    public function return_html(){
        redirect('User/index/index', 2, '支付成功');
        /*require './ThinkPHP/Library/Org/Pay/NPay.class.php';
        $appid = '1005632156';
        $appsecret = '0cc15faf3d2c9a80e4f646e790f3cc38';
        $pay = new \NPay($appid,$appsecret);

        $v = I('');
        $mac = $pay->mac($v);
        // TO DO SOMETHING
        if($v['v_mac'] == $mac) {
            //process the save task
            redirect('User/index/index', 2, '支付成功');
        } else {
            //log if check is fail
            redirect('User/index/index', 2, "<font color='red'>支付失败....</font>");
        }*/
    }
    //异步通知地址
    public function NJ_Pay_return(){
        //require './ThinkPHP/Library/Org/Pay/NPay.class.php';
        $appid = '1005632168';
        $appsecret = '0cc15faf3d2c9a80e4f646e790f3cc38';
        //$pay = new \NPay($appid,$appsecret);

        $data['v_oid']          = I('orderNum');          //订单号
        $data['v_pmode ']       = I('payWay');            //支付方式 默认0
        $data['v_pstatus']      = I('status');            //支付状态 1成功 0失败
        $data['v_amount']       = I('amount');            //支付金额
        $data['v_moneytype']    = I('moneyType');         //支付币种 默认156人民币
        //$data['v_mac']          = I('v_mac');           //支付验签
        //$data2 = var_export($data,true);
        //file_put_contents(date('Ymd-His')."006".".txt",$data2);
        //$mac = $pay->mac($data);
        // TO DO SOMETHING
        if($data['v_pstatus']==1){
            $v_oid = $data['v_oid'] ;            //转账ID 加 用户账户
            $data1=  explode('-',$v_oid);
            $id   =  $data1[0];
            $mt4  =  $data1[1];
            $comment = 'deposit#';
            $set = M('into_gold_set')->where(['belong_pay'=>1])->find();
            $rate = $set['rate'];
            $fee = $set['fee'];
            $max_fee = $set['max_fee'];

            if($max_fee==0 || $max_fee==''){
                $save['counter_fee'] = round(($data['v_amount']/$rate)*$fee,2);
                $save['final_money'] = round(($data['v_amount']/$rate),2)- $save['counter_fee'];
            }else if ((($data['v_amount']/$rate)-$max_fee)<0){
                $save['counter_fee'] = round(($data['v_amount']/$rate)*$fee,2);
                $save['final_money'] = round(($data['v_amount']/$rate),2)-$save['counter_fee'];
            }else{
                $save['counter_fee'] = $max_fee;
                $save['final_money'] =round(($data['v_amount']/$rate)-$max_fee,2);
            }
            $save['status'] =2;
            $order = M('into_gold')->where(array('id'=>$id,'status'=>2))->find();
            if(empty($order)){
                $into = M('into_gold')->where(array('id'=>$id))->save($save);
                if($into!==false){
                    echo "ok";
                    $user_data = M('user')->where(array('user_id'=>$mt4))->field('user_email,type')->find();
                    if($user_data['type']==1){
                        $request = "action=bulkchangebalance&logins=$mt4&value=".$save['final_money']."&comment=$comment$id\0";
                        mt4_operation_digital($request);
                    }else{
                        $request = "action=bulkchangebalance&logins=$mt4&value=".$save['final_money']."&comment=$comment$id\0";
                        mt4_operation($request);
                    }
                    $address = $user_data['user_email'];
                    $title   = '入金成功';
                    $message = "尊敬的凯富联合用户<br/>：$mt4 ,<br/>您已成功入金：$".$save['final_money']."<br/>入金订单号:$id";
                    SendMail($address, $title, $message);
                    exit;
                }else{
                    echo('系统出错,请联系客服');
                }
            }else {
                echo "checkok";
                exit;
            }

        }else{
            //$data2 = var_export($mac,true);
            file_put_contents(date('Ymd-His')."006".".txt",$data2);
        }
    }
    //睿联支付
    public function ruilian(){
		echo '支付通道已关闭';die;
        $user = session('user');
        if(empty($user)){redirect('Index/login', 1, '身份信息过期，正在跳转登录页面...');}    //session为空跳转到登陆页
        //if(($user['user_id']!=250110) && ($user['user_id']!=250107)){die('入金关闭');}
        $set = M('into_gold_set')->where(['belong_pay'=>1])->find();
        $money = I('usd')?I('usd'):die("入金金额不得为空");
        $bank = I('bank')?I('bank'):'ruilian';//支付银行码
        if($bank!='03'){die('Channel error, please try again!');}
        $data['appType']=$bank;//支付方式
        $data['cardType']=I('cardType') ? I('cardType') : 'baomt';//支付卡种
        if(!is_numeric($money)){echo "<font color='red'>交易金额必须是数字。</font>";exit;}
        if($money<$set['minimum']){echo "<font color='red'>入金金额不得低于".$set['minimum']."</font>";exit;}

        $add['mt4'] = $user['user_id'];
        $add['money'] = round($money,2);
        $add['rate'] = $set['rate'];
        $add['modu'] = $set['name'];
        $add['into_time'] = time();
        $add['status'] = 1;
        //if($user['user_id']!=250107){die;}
        $into_add = M('into_gold')->add($add);
        if($into_add){
            $merOrderNum = $into_add.'-'.$user['user_id'];      //订单号**********
            $tranAmt = round($add['money']*$set['rate'],2);                //交易金额*********
            $frontMerUrl =  'http://'.$_SERVER['SERVER_NAME'].'/index.php/User/Capital/return_html';//商户前台通知地址**********
            $backgroundMerUrl = 'http://'.$_SERVER['SERVER_NAME'].'/index.php/User/Capital/ruilianReturn';//商户后台通知地址**********

            $pay_memberid = "10162";   //商户ID
            $pay_orderid = $merOrderNum;    //订单号
            $pay_amount = $tranAmt;    //交易金额
            $pay_applydate = date("Y-m-d H:i:s");  //订单时间
            $pay_bankcode = "912";   //交易类型编码 网银直连912
            $pay_notifyurl = $backgroundMerUrl;   //服务端返回地址
            $pay_callbackurl = $frontMerUrl;  //页面跳转返回地址
            $Md5key = "uj92f2j938a9vr2i48xqezpikgjrr2fu";   //密钥
            $tjurl = "http://www.silverspay.com/Pay_Index.html";   //提交地址
            $requestarray = array(
                "pay_memberid" => $pay_memberid,
                "pay_orderid" => $pay_orderid,
                "pay_amount" => $pay_amount,
                "pay_applydate" => $pay_applydate,
                "pay_bankcode" => $pay_bankcode,
                "pay_notifyurl" => $pay_notifyurl,
                "pay_callbackurl" => $pay_callbackurl
            );
            ksort($requestarray);
            reset($requestarray);
            $md5str = "";
            foreach ($requestarray as $key => $val) {
                $md5str = $md5str . $key . "=" . $val . "&";
            }
            echo($md5str . "key=" . $Md5key."<br>");
            $sign = strtoupper(md5($md5str . "key=" . $Md5key));
            $requestarray["pay_md5sign"] = $sign;
            #################################################################################
            $requestarray["gate"] = '';//<<<<<<<<<<<<<<<<<<<<<银行编码,不参与签名,参照文档
            #################################################################################
            $str = '<form id="Form1" name="Form1" method="post" action="' . $tjurl . '">';
            foreach ($requestarray as $key => $val) {
                $str = $str . '<input type="hidden" name="' . $key . '" value="' . $val . '">';
            }
            //$str = $str . '<input type="submit" value="提交">';
            $str = $str . '</form>';
            $str = $str . '<script>';
            $str = $str . 'document.Form1.submit();';
            $str = $str . '</script>';
            exit($str);
        }else{
            echo('系统出错,请联系客服');
        }
    }
    public function ruilianReturn(){//睿联支付回调
        $ReturnArray['memberid']=I('memberid') ? I('memberid') : die('error-memberid');// 商户ID
        $ReturnArray['orderid']=I('orderid') ? I('orderid') : die('error-orderid');// 订单号
        $ReturnArray['amount']=I('amount') ? I('amount') : die('error-amount');// 交易金额
        $ReturnArray['datetime']=I('datetime') ? I('datetime') : die('error-datetime');// 交易时间
        $ReturnArray['returncode']=I('returncode') ? I('returncode') : die('error-returncode');
        $ReturnArray['transaction_id']=I('transaction_id') ? I('transaction_id') : die('error-transaction_id');
        $Md5key = "uj92f2j938a9vr2i48xqezpikgjrr2fu";
        ///////////////////////////////////////////////////////
        ksort($ReturnArray);
        reset($ReturnArray);
        $md5str = "";
        foreach ($ReturnArray as $key => $val) {
            $md5str = $md5str . $key . "=" . $val . "&";
        }
        $sign = strtoupper(md5($md5str . "key=" . $Md5key));
        ///////////////////////////////////////////////////////
        $data = var_export($ReturnArray,true);
        file_put_contents('Uploads/ruilian/'.$ReturnArray['orderid']."-data.txt",$data);
        if ($sign == $_REQUEST["sign"]) {
            if (I('returncode') == "00") {
//                $str = "交易成功！订单号：".$_REQUEST["orderid"];
//                file_put_contents("Uploads/ruilian/success.txt",$str."\n", FILE_APPEND);

                $data1=  explode('-',$ReturnArray['orderid']);//转账ID 加 用户账户
                $id   =  $data1[0];
                $mt4  =  $data1[1];
                $comment = 'deposit#';
                $set = M('into_gold_set')->where(['belong_pay'=>1])->find();
//                $rate = $set['rate'];
                $fee = $set['fee'];
                $max_fee = $set['max_fee'];

                $order = M('into_gold')->where(array('id'=>$id,'status'=>1))->find();
                if(!empty($order)){
                    $rate = $order['rate'];
                    if($max_fee==0 || $max_fee==''){
                        $save['counter_fee'] = round(($ReturnArray['amount']/$rate)*$fee,2);
                        $save['final_money'] = round(($ReturnArray['amount']/$rate),2)- $save['counter_fee'];
                    }else if ((($ReturnArray['amount']/$rate)-$max_fee)<0){
                        $save['counter_fee'] = round(($ReturnArray['amount']/$rate)*$fee,2);
                        $save['final_money'] = round(($ReturnArray['amount']/$rate),2)-$save['counter_fee'];
                    }else{
                        $save['counter_fee'] = $max_fee;
                        $save['final_money'] =round(($ReturnArray['amount']/$rate)-$max_fee,2);
                    }
                    $save['status'] =2;
                    $into = M('into_gold')->where(array('id'=>$id))->save($save);
                    if($into!==false){
                        echo "ok";
                        $user_data = M('user')->where(array('user_id'=>$mt4))->field('user_email')->find();
                        if($user_data['type']==1){
                            $request = "action=bulkchangebalance&logins=$mt4&value=".$save['final_money']."&comment=$comment$id\0";
                            mt4_operation_digital($request);
                        }else{
                            $request = "action=bulkchangebalance&logins=$mt4&value=".$save['final_money']."&comment=$comment$id\0";
                            mt4_operation($request);
                        }
                        $address = $user_data['user_email'];
                        $title   = '入金成功';
                        $message = "尊敬的凯富联合用户<br/>：$mt4 ,<br/>您已成功入金：$".$save['final_money']."<br/>入金订单号:$id";
                        SendMail($address, $title, $message);
                        exit;
                    }else{
                        echo('系统出错,请联系客服');
                    }
                }else{
                    exit("ok");
                }
            }
        }else{
            file_put_contents('Uploads/ruilian/'.$ReturnArray['orderid']."-data-err.txt",'验签失败');
        }
    }

    /***
     *  汇潮支付
     *
     */
    public function huiCao_pay(){
        $user = session('user');
        if(empty($user)){die('身份信息过期...');}    //session为空跳转到登陆页
        $userState=M('user')->where(['user_id'=>$user['user_id']])->field('status')->find();
        if($userState['status']!=3){
            die('您的账号还未申请实名认证，请实名认证通过后在进行入金');
        }
        $set = M('into_gold_set')->where(['belong_pay'=>2])->find();
        if($set['state']!=1){die("入金通道未开启");}
        $money = I('usd')?I('usd'):die("入金金额不得为空");
        $bankCode = I('bankCode')?I('bankCode'):''; //银行编码
        if(!is_numeric($money)){echo "<font color='red'>交易金额必须是数字。</font>";exit;}
        if($money<$set['minimum']){echo "<font color='red'>入金金额不得低于".$set['minimum']."</font>";exit;}
        $add['mt4'] = $user['user_id'];
        $add['money'] = round($money,2);
        $add['rate'] = $set['rate'];
        $add['modu'] = $set['name'];
        $add['into_time'] = time();
        $add['final_money'] = 0;
        $add['counter_fee'] = 0;
        $add['status'] = 1;
        $into_add = M('into_gold')->add($add);
        if($into_add){
            $ReturnArray['merOrderId']=   $into_add.'-'.$user['user_id'];    // 订单号
            $ReturnArray['merchantId']  = '999603053310001'; // 商户ID
            $ReturnArray['cardType']    = 'debit';        // 银行卡类型
            $ReturnArray['accountType'] = 'personal';     //账户类型
            $ReturnArray['bankCode']    = $bankCode;      // 银行编码
            $ReturnArray['orderAmt']    =  round(($money*$set['rate'])*100,2);  // 交易金额(分)
            $ReturnArray['returnUrl']='';                  // 前端回调页面地址 [回调地址不可以填写参数]
            $ReturnArray['notifyUrl']='http://www.kfhijfx.com/index.php/User/capital/huiCao_pay_return';// 后端回调地址
            $ReturnArray['goodsName']='intogold';// 商品名称
            $ReturnArray['timeStamp']=date('YmdHis');// 交易时间
            $ke = "5ff98ae457578602";
            $pay_data = array_filter($ReturnArray);//除空
            ksort($pay_data);//从小到大排序
            $str = "";
            foreach ($pay_data as $key => $val) {
                $str = $str . $key . "=" . $val . "&";
            }
            $sign = md5($str."key=".$ke);
            $serverUrl =' http://bill.huibillpu.com/ZfGateway/direct/Bank/webOrder.do';
            $html = "<form name='toPay' action='" .$serverUrl . "' method='POST'>\r";
            $html .= "<input type='hidden' name='merchantId' value='" . $ReturnArray['merchantId'] . "'>\r";
            $html .= "<input type='hidden' name='merchantId' value='" . $ReturnArray['merchantId'] . "'>\r";
            $html .= "<input type='hidden' name='cardType' value='" . $ReturnArray['cardType'] . "'>\r";
            $html .= "<input type='hidden' name='accountType' value='" . $ReturnArray['accountType'] . "'>\r";
            $html .= "<input type='hidden' name='bankCode' value='" . $ReturnArray['bankCode'] . "'>\r";
            $html .= "<input type='hidden' name='orderAmt' value='" . $ReturnArray['orderAmt'] . "'>\r";
            $html .= "<input type='hidden' name='merOrderId' value='" . $ReturnArray['merOrderId'] . "'>\r";
            $html .= "<input type='hidden' name='returnUrl' value='" . $ReturnArray['returnUrl'] . "'>\r";
            $html .= "<input type='hidden' name='notifyUrl' value='" . $ReturnArray['notifyUrl'] . "'>\r";
            $html .= "<input type='hidden' name='goodsName' value='" . $ReturnArray['goodsName'] . "'>\r";
            $html .= "<input type='hidden' name='timeStamp' value='" . $ReturnArray['timeStamp'] . "'>\r";
            $html .= "<input type='hidden' name='sign' value='".$sign."'>\r";
            $html .= "</form>";
            $html .= "<script>document.forms['toPay'].submit();</script>";
            echo $html;
        }else{
            echo('系统出错,请联系客服');
        }
    }
    public function huiCao_pay_return(){
        $data['merId']      = I('merId')?I('merId'):'';          //商户号
        $data['merOrderId'] = I('merOrderId')?I('merOrderId'):'';//订单号
        $data['orderDate']  = I('orderDate')?I('orderDate'):'';  //支付时间
        $data['tranAmt']    = I('tranAmt')?I('tranAmt'):'';  //支付金额(分)
        $data['settStat']   = I('settStat')?I('settStat'):'';   //结算状态:00:表示结算成功
        $data['resCdoe']    = I('resCdoe')?I('resCdoe'):'';     //返回结果:0000:表示支付成功
        $data['resMsg']     = I('resMsg')?I('resMsg'):'';       //结果描述
        $DataSign               = I('sign')?I('sign'):'';           //结果描述
        $data2 = var_export($data,true);
        file_put_contents('PayLog/'.date('Ymd-His')."001".".txt","Data".$data2);
        $key = '5ff98ae457578602';           //密匙

        $pay_data = array_filter($data);//除空
        ksort($pay_data);//从小到大排序
        $str = "";
        foreach ($pay_data as $k => $v) {
            $str = $str . $k . "=" . $v . "&";
        }
        $sign = md5($str."key=".$key);
        if($DataSign==$sign){
            if($data['resCdoe']==0000){
                $merOrderId = $data['merOrderId'] ;            //转账ID 加 用户账户
                $data1=  explode('-',$merOrderId);
                $id   =  $data1[0];
                $mt4  =  $data1[1];
                $comment = 'deposit#';
                $set = M('into_gold_set')->where(['belong_pay'=>2])->find();
                $rate = $set['rate'];
                $fee = $set['fee'];
                $max_fee = $set['max_fee'];
                $tranAmt = round($data['tranAmt']/100,2);//把单位换算成元
                if($max_fee==0 || $max_fee==''){
                    $save['counter_fee'] = round(($tranAmt/$rate)*$fee,2);
                    $save['final_money'] = round(($tranAmt/$rate),2)- $save['counter_fee'];
                }else if ((($tranAmt/$rate)-$max_fee)<0){
                    $save['counter_fee'] = round(($tranAmt/$rate)*$fee,2);
                    $save['final_money'] = round(($tranAmt/$rate),2)-$save['counter_fee'];
                }else{
                    $save['counter_fee'] = $max_fee;
                    $save['final_money'] =round(($tranAmt/$rate)-$max_fee,2);
                }
                $save['status'] =2;
                $data3 = var_export($save,true);
                file_put_contents(date('Ymd-s')."008".".txt",$data3);

                $order = M('into_gold')->where(array('id'=>$id,'status'=>2))->find();
                if(empty($order)){
                    $into = M('into_gold')->where(array('id'=>$id))->save($save);
                        if($into!==false){
                            echo "success";
                            $user_data = M('user')->where(array('user_id'=>$mt4))->field('user_email,type')->find();
                            if($user_data['type']==1){
                                $request = "action=bulkchangebalance&logins=$mt4&value=".$save['final_money']."&comment=$comment$id\0";
                                mt4_operation_digital($request);
                            }else{
                                $request = "action=bulkchangebalance&logins=$mt4&value=".$save['final_money']."&comment=$comment$id\0";
                                mt4_operation($request);
                            }
                            $address = $user_data['user_email'];
                            $title   = '入金成功';
                            $message = "尊敬的凯富联合用户<br/>：$mt4 ,<br/>您已成功入金：$".$save['final_money']."<br/>入金订单号:$id";
                            SendMail($address, $title, $message);
                            exit;
                        }else{
                            echo "success";
                            echo('系统出错,请联系客服');
                        }
                    }else {
                        echo "success";exit;
                    }
            }else{
                file_put_contents('PayLog/'.date('Ymd-s')."003".".txt",$data['settStat']);
				 echo "success";exit;
            }

        }else{
            file_put_contents('PayLog/'.date('Ymd-s')."002".".txt",$DataSign.'--'.$sign);
            echo "success";
        }

    }



    //验证码
    function checkcode(){
        //导入图片类
        $config = array(
            'fontSize' => 15,   // 验证码字体大小
            'length' => 4,      // 验证码位数
            'useNoise' => true, // 关闭验证码杂点
        );
        ob_clean();
        $Verify = new \Think\Verify($config);
        $Verify->entry();
    }
    //验证码检查
    public function verify_date(){
        //验证码检查
        $verify = I('verify');
        if($verify !=null){
            if(!check_verify($verify)){
                $this->ajaxReturn(array('error'=>"验证码错误",'status'=>0));
            }else{
                $this->ajaxReturn(array('msg'=>"",'status'=>1));
            }
        }else{
            $this->ajaxReturn(array('error'=>"必填",'status'=>0));
        }

    }
    //入金历史
    public function into_gold_history(){
        $user = session('user');
        if(empty($user)){redirect('Index/login', 1, '身份信息过期，正在跳转登录页面...');}    //session为空跳转到登陆页

        $fo = I('fo') ? strtotime(I('fo')) : "";
        $to = I('to') ? strtotime(I('to')): "";
        $status = I('status') ? I('status'):"";
        $id = I('id') ? I('id') : "";
        if(!empty($id)){
            $where['id'] = $id;
        }
        if(!empty($status)){
            $where['status'] = $status;
        }
        if(!empty($fo) && !empty($to)){
            $where['into_time'] = array('between',array($fo,$to.' 23:59:59'));
        }
        if(empty($where)){
            $where['mt4'] = $user['user_id'];
            $count = M('into_gold')->where($where)->count();
            $Page = new \Think\Page($count, 10);
            $show = $Page->show();// 分页显示输出
            $data = M('into_gold')->where($where)->order('id desc')->limit($Page->firstRow . ',' . $Page->listRows)->select();
        } else  {
            $where['mt4'] = $user['user_id'];
            $count = M('into_gold')->where($where)->count();
            $Page = new \Think\Page($count, 10);
            $Page->parameter['id']=$id;
            $Page->parameter['fo']=date('Y-m-d',$fo);
            $Page->parameter['to']=date('Y-m-d',$to);
            $Page->parameter['status']=$status;
            $show = $Page->show();// 分页显示输出
            $data = M('into_gold')->where($where)->order('id desc')->limit($Page->firstRow . ',' . $Page->listRows)->select();
        }
        foreach ($data as $k=>$v){
           $data[$k]['into_time'] = timeFormat($v['into_time']);
            if($v['status']==1){
                $data[$k]['status']="<font color='#bc8f8f'>未付款</font>";
            }else if($v['status']==2){
                $data[$k]['status']="<font color='green'>已到账</font>";
            }else if($v['status']==3){
                $data[$k]['status']="<font color='red'>未到账</font>";
            }
        }

        $this->assign('fo',date('Y-m-d H:i:s',$fo));
        $this->assign('to',date('Y-m-d H:i:s',$to));
        $this->assign('id',$id);
        $this->assign('status',$status);
        $this->assign('page',$show);
        $this->assign('data',$data);
        $this->display();
    }

    /**
     *  出金
     *
     */
    //出金申请页
    public function Gold(){
        $user = session('user');
        if(empty($user)){redirect('Index/login', 1, '身份信息过期，正在跳转登录页面...');}
        $mt4_users = M('mt4_users', '', 'DB_CONFIG2');//数据库
//        if($user['type']==1){
//            $mt4_users = M('mt4_trades', '', 'DB_CONFIG3');//数字
//        }else{
//            $mt4_users = M('mt4_trades', '', 'DB_CONFIG2');//外汇
//        }
        $bank_id = I('bankID')?I('bankID'):'';
        $user_state = M('user')->where(['user_id'=>$user['user_id']])->field('user_id,name_zh_cn,user_email,user_phone,status')->find();//用户信息
        if($user_state['status']!=3){
            die('您的账号还未申请实名认证，请实名认证通过后在进行出金');
        }
        $set = M('gold_set')->where(array('state'=>1))->find();                         //出金设置
        $user_bank = M('user_bank')->where(array('mt4'=>$user['user_id']))->select();   //银行卡信息
        $bank_list = M('bank')->select();                                                //银行列表
        $adds = M('region')->where(['pid'=>0])->select();                               //地址选择

        $gold = M('gold')->where('(status < 3) and (mt4='.$user['user_id'].')')->sum('usd');        //正出金金额
        $balance = $mt4_users->where(array('LOGIN'=>$user['user_id']))->field('BALANCE')->find();   //余额
		//print_r($balance);die;
        $rate=M('into_gold_set')->field('rate')->where(['type'=>1,'state'=>1])->find();//本月
        $balance['balanceAir1']=($balance['balance']-$gold)*($rate['rate']*0.0115+$rate['rate']);
        $balance['balanceAir2']=($balance['balance']-$gold)*($rate['rate']*0.0325+$rate['rate']);

        $set['remarks']= htmlspecialchars_decode($set['remarks']);//出金说明
        $bank_data='';
        if(!empty($bank_id)){
            $bank_data= M('user_bank')->where(['id'=>$bank_id])->find();        //银行卡直接付款
        }
        $this->assign('bank_data',$bank_data);
        $this->assign('adds',$adds);
        $this->assign('bank',$user_bank);
        $this->assign('bank_list',$bank_list);
        $this->assign('balance',$balance);
        $this->assign('gold',round($gold,2));
        $this->assign('available',round($balance['balance']-$gold,2));//可用
        $this->assign('user',$user);
        $this->assign('set',$set);
        $this->display();
    }
    //地址联动
    public function region(){
        $name = I('name');
        if($name){
            $pid = M('region')->where(['name'=>$name])->field('id')->find();
            $data = M('region')->where(['pid'=>$pid['id']])->select();
            if($data){
                $this->ajaxReturn(array('msg'=>$data,'status'=>1));
            }else{
                $this->ajaxReturn(array('error'=>"没有信息",'status'=>0));
            }
        }
    }
    //出金申请写入
    public function Gold_Add_Apply(){
        $user = session('user');
        if(empty($user)){$this->ajaxReturn(array('error'=>"信息无效,请刷新重试",'status'=>0));exit;}
        $user_state=M('user')->where(['user_id'=>$user['user_id']])->field('status')->find();
        if($user_state['status']!=3){
            die('您的账号还未申请实名认证，请实名认证通过后在进行出金');
        }

        $set = M('gold_set')->where(['state'=>1])->find();//出金设置
        if(empty($set)){  $this->ajaxReturn(array('error'=>"出金通道未开启",'status'=>0));exit;}
			
        $data['mt4'] = $user['user_id'];
        $data['user_name'] = $user['name_zh_cn'];
        $data['bank_username'] = I('post.bank_user_name')?I('post.bank_user_name'):$this->ajaxReturn(array('error'=>"持卡人姓名不可为空",'status'=>0));
        $data['usd'] = I('post.usd')?I('post.usd'):$this->ajaxReturn(array('error'=>"金额不可为空",'status'=>0));
        $data['bank'] = I('post.bank')?I('post.bank'):$this->ajaxReturn(array('error'=>"开户行不可为空",'status'=>0));
        $data['bank_number'] = I('post.bank_number')?I('post.bank_number'):$this->ajaxReturn(array('error'=>"银行卡号不可为空",'status'=>0));
        $data['bank_name'] = I('post.bank_zhi')?I('post.bank_zhi'):$this->ajaxReturn(array('error'=>"支行名称不可为空",'status'=>0));
        $data['area_1'] = I('post.adds')?I('post.adds'):$this->ajaxReturn(array('error'=>"银行地址不可为空",'status'=>0));
        $data['area_2'] = I('post.city')?I('post.city'):$this->ajaxReturn(array('error'=>"银行城市不能为空",'status'=>0));
        $data['gold_time']=time();
		if($data['usd']<$set['min_into']){
			$this->ajaxReturn(array('error'=>"最低提现".$set['min_into'],'status'=>0));exit;
		}
		if($data['usd']>$set['max_into']){
			$this->ajaxReturn(array('error'=>"最高提现".$set['max_into'],'status'=>0));exit;
		}
		
		
		
		
        $mt4_users = M('mt4_users', '', 'DB_CONFIG2');//数据库
        //        if($user['type']==1){
//            $mt4_users = M('mt4_trades', '', 'DB_CONFIG3');//数字
//        }else{
//            $mt4_users = M('mt4_trades', '', 'DB_CONFIG2');//外汇
//        }

        $where['LOGIN']=$user['user_id'];
        $balance = $mt4_users->field('BALANCE')->where($where)->find();//余额
        /*$request = "action=getaccountbalance&login=".$data['mt4']."\0";  //余额
        $reoups = mt4_operation($request);
        parse_str($reoups,$size);*/

		$gold_where['mt4']=$data['mt4'];
		$gold_where['status']=array('lt',3);
		
        $gold = M('gold')->where($gold_where)->sum('usd');       //正出金金额
        if($balance['balance']<($data['usd']+$gold)){                     //如果 (总余额)小于(出金金额)和(正出金金额)
            $this->ajaxReturn(array('error'=>"出金金额不得大于现有余额",'status'=>0));exit;
        }
        /*$firstday = date("Y-m-d");
        $last_month=strtotime($firstday." -1 month")+1;
        $currentday = date("Y-m-0");
        $current_month=strtotime($currentday);
        $airline=M('into_gold')->where('into_time >'.$last_month)->sum('final_money');//未到期总和
        $airline_current=M('into_gold')->where('into_time >'.$current_month)->sum('final_money');//本月总和
        $rate1=M('into_gold_set')->field('rate')->where(['type'=>1,'state'=>1])->find();//本月
        $rate2=M('into_gold_set')->field('rate')->where(['type'=>2,'state'=>1])->find();//上月*/

        if(empty($set['max_fee'])){                  //当最高手续费为空时，取没笔%的手续费-$set['fee']
            $data['fee'] = sprintf("%.2f",($data['usd']*($set['fee'])));   //手续费
            /*if($data['usd']>$airline){
                $data['rmb']=($data['usd']-($airline-$airline_current))*$rate1['rate']+($airline-$airline_current)*$rate2['rate'];
            }else if($data['usd']>$airline_current){
                $data['rmb']=($data['usd']-$airline_current)*$rate2['rate']+($airline_current*$rate1['rate']);
            }else{
                $data['rmb']=$data['usd']*$rate1['rate'];
            }*/
            $data['rmb'] = sprintf("%.2f",((($data['usd'])-($data['fee']))* $set['rate']));   //出金金额（除去手续费后的）
        }else if(($data['usd']-$set['max_fee'])<1) {                 //最高手续费不为空
            $data['fee'] = sprintf("%.2f", $data['usd'] * ($set['fee']));   //手续费
            $data['rmb'] = sprintf("%.2f", ((($data['usd']) - ($data['fee'])) * $set['rate']));   //出金金额（除去手续费后的）
            /*$usd=$data['usd'] - $data['fee'];
            if($data['usd']>$airline){
                $data['rmb']=($usd-($airline-$airline_current))*$rate1['rate']+($airline-$airline_current)*$rate2['rate'];
            }else if($usd>$airline_current){
                $data['rmb']=($usd-$airline_current)*$rate2['rate']+($airline_current*$rate1['rate']);
            }else{
                $data['rmb']=$usd*$rate1['rate'];
            }*/
        }else{
            $data['fee']= $set['max_fee'];
            $data['rmb'] = sprintf("%.2f", ((($data['usd']) - ($set['max_fee'])) * $set['rate']));   //出金金额（除去手续费后的）

            /*$usd=$data['usd'] - $set['max_fee'];
            if($data['usd']>$airline){
                $data['rmb']=($usd-($airline-$airline_current))*$rate1['rate']+($airline-$airline_current)*$rate2['rate'];
            }else if($usd>$airline_current){
                $data['rmb']=($usd-$airline_current)*$rate2['rate']+($airline_current*$rate1['rate']);
            }else{
                $data['rmb']=$usd*$rate1['rate'];
            }*/
        }
        $data['rmb']=round($data['rmb'],2);
        $data['rate'] = $set['rate'];//$rate1['rate'];
        $add = M('gold')->add($data);
        if($add){
            $this->ajaxReturn(array('msg'=>"申请提交成功",'status'=>1));
        }else{
            $this->ajaxReturn(array('error'=>"申请提交失败",'status'=>0));
        }
    }
    //出金历史
    public function Gold_history(){
        $user = session('user');
        if(empty($user)){redirect('Index/login', 1, '身份信息过期，正在跳转登录页面...');}
        $fo = I('fo') ? strtotime(I('fo')) : "";
        $to = I('to') ? strtotime(I('to')) : "";
        $status = I('status') ? I('status') : 0;
        $where= '';
        if(!empty($fo) && !empty($to)){
            $where['gold_time'] = array('between',array($fo,$to.' 23:59:59'));
        }
        if(!empty($status)){
            $where['status'] = $status;
        }
        $where['mt4'] = $user['user_id'];
        if(!empty($where)) {
            $count = M('gold')->where($where)->count();
            $Page = new \Think\Page($count, 15);
            $Page->parameter['fo'] = date('Y-m-d', $fo);
            $Page->parameter['to'] = date('Y-m-d', $to);
            $Page->parameter['status'] = $status;
            $show = $Page->show();// 分页显示输出
            $data = M('gold')->where($where)->limit($Page->firstRow . ',' . $Page->listRows)->order('id desc')->select();
            foreach ($data as $k=>$v) {
                if ($v['status'] == 1) {
                    $data[$k]['state'] = "<font color='#bc8f8f'>待审核</font>";
                } else if ($v['status'] == 2) {
                    $data[$k]['state'] = "<font color='#556b2f'>处理中</font>";
                } else if ($v['status'] == 3) {
                    $data[$k]['state'] = "<font color='green'>已受理</font>";
                } else if ($v['status'] == 4) {
                    $data[$k]['state'] = "<font color='red'>未通过</font>";
                }
            }
        }
        $this->assign('to', date('Y-m-d', $to));
        $this->assign('fo', date('Y-m-d', $fo));
        $this->assign('status', $status);
        $this->assign('page',$show);
        $this->assign('user',$user);
        $this->assign('data',$data);
        $this->display();
    }
    //出金单个详情
    public function Gold_OneData(){
        $id = I('id');
        if(empty($id)){echo "没有获取到信息";exit;}
        $data = M('gold')->where(['id'=>$id])->find();
        if(empty($data)){echo "没有获取到信息";exit;}
        if($data['status']==1){
            $data['state'] = "<font color='#bc8f8f'>待审核</font>";
        }else if($data['status']==2){
            $data['state'] = "<font color='#556b2f'>处理中</font>";
        }else if($data['status']==3){
            $data['state'] = "<font color='green'>已受理</font>";
        }else{
            $data['state'] = "<font color='red'>未成功</font>";
        }

        $this->assign('data',$data);
        $this->display();
    }
    //出金撤销申请
    public function drawing_Revoke(){
       $id = I('id')?I('id'):$this->ajaxReturn(array('error'=>"没有获取到信息,请重试",'status'=>0));
       $Revoke = M('gold')->where(['id'=>$id])->save(['status'=>4,'reason'=>"用户撤销了申请"]);
        if($Revoke){
            $this->ajaxReturn(array('msg'=>"撤销成功",'status'=>1));
        }else{
            $this->ajaxReturn(array('error'=>"撤销失败",'status'=>0));
        }
    }

    /**
     * 银行卡管理
     *
     * */
    public function bank_list(){
        $user =session('user');
        if(!empty($user)){
            $data = M('user_bank')->where(['mt4'=>$user['user_id']])->select();

            $this->assign('data',$data);
            $this->display();
        }else{
            //redirect('Index/login', 1, '身份信息过期，正在跳转登录页面...');
            echo "身份信息过期";exit;
        }
    }
    //银行卡添加
    public function bank_add(){
        $user =session('user');
        if(empty($user)){$this->ajaxReturn(array('error'=>"身份信息过期",'status'=>0));exit;}
        if(empty($_POST)){
            $bank_list = M('bank')->select();                  //银行列表
            $adds = M('region')->where(['pid'=>0])->select();  //地址选择

            $this->assign('adds',$adds);
            $this->assign('bank_list',$bank_list);
            $this->display();
        }else{
            $data['mt4']= $user['user_id'];
            $data['user_name'] = I('user_name')?I('user_name'):die($this->ajaxReturn(array('error'=>"姓名不能为空",'status'=>0)));
            $data['bank_number'] = I('bank_number')?I('bank_number'):die($this->ajaxReturn(array('error'=>"卡号不能为空",'status'=>0)));
            $data['bank_adds'] = I('bank_adds')?I('bank_adds'):die($this->ajaxReturn(array('error'=>"所在省不能为空",'status'=>0)));
            $data['bank_city'] = I('bank_city')?I('bank_city'):die($this->ajaxReturn(array('error'=>"所在市不能为空",'status'=>0)));
            $data['bank_name'] = I('bank_name')?I('bank_name'):die($this->ajaxReturn(array('error'=>"银行名称不能为空",'status'=>0)));
            $data['bank_branch'] = I('bank_branch')?I('bank_branch'):die($this->ajaxReturn(array('error'=>"支行名不能为空",'status'=>0)));

            $add = M('user_bank')->add($data);
            if($add){
                $this->ajaxReturn(array('msg'=>"添加成功",'status'=>1));
            }else{
                $this->ajaxReturn(array('error'=>"添加失败",'status'=>0));
            }
        }
    }
    //银行卡修改
    public function bank_save(){
        $id = I('id');
        if(empty($id)){echo "没有信息";exit;}
        $data = M('user_bank')->where(['id'=>$id])->find();
        if($data){
            $bank_list = M('bank')->select();                                                //银行列表
            $adds = M('region')->where(['pid'=>0])->select();                               //地址选择

            $this->assign('adds',$adds);
            $this->assign('bank_list',$bank_list);
            $this->assign('data',$data);
            $this->display();
        }
    }
    //银行卡数据更新
    public function bank_saveData(){
        $user = session('user');
        if(empty($user)){$this->ajaxReturn(array('error'=>"您的账号信息失效,请重新登录",'status'=>0));exit;}
        $data['mt4'] = $user['user_id'];
        $id = I('get.id')?I('id'):die($this->ajaxReturn(array('error'=>"信息错误",'status'=>0)));

        $data['user_name'] = I('user_name')?I('user_name'):die($this->ajaxReturn(array('error'=>"姓名不能为空",'status'=>0)));
        $data['bank_number'] = I('bank_number')?I('bank_number'):die($this->ajaxReturn(array('error'=>"卡号不能为空",'status'=>0)));
        $data['bank_adds'] = I('bank_adds')?I('bank_adds'):die($this->ajaxReturn(array('error'=>"所在省不能为空",'status'=>0)));
        $data['bank_city'] = I('bank_city')?I('bank_city'):die($this->ajaxReturn(array('error'=>"所在市不能为空",'status'=>0)));
        $data['bank_name'] = I('bank_name')?I('bank_name'):die($this->ajaxReturn(array('error'=>"银行名称不能为空",'status'=>0)));
        $data['bank_branch'] = I('bank_branch')?I('bank_branch'):die($this->ajaxReturn(array('error'=>"支行名不能为空",'status'=>0)));

        $save = M('user_bank')->where(['id'=>$id])->save($data);
        if($save!==false){
            $this->ajaxReturn(array('msg'=>"修改成功",'status'=>1));
        }else{
            $this->ajaxReturn(array('error'=>"修改失败",'status'=>0));
        }

    }
    //银行卡删除
    public function Bank_delete(){
        $id = I('id');
        if(empty($id)){$this->ajaxReturn(array('error'=>"没有信息",'status'=>0));exit;}
        $delete = M('user_bank')->where(['id'=>$id])->delete();
        if($delete){
            $this->ajaxReturn(array('msg'=>'删除成功','status'=>1));
        }else{
            $this->ajaxReturn(array('error'=>'删除失败','status'=>0));
        }
    }

}